//
//  MyBriefcaseViewController.m
//  MISCloud
//
//  Created by goldeney on 13-3-21.
//  Copyright (c) 2013年 goldeneye. All rights reserved.
//

#import "OAMyBriefcaseViewController.h"
#import "GETableViewButtonCell.h"
#import "OAMyBriefcaseClassCell.h"

#import "MJRefresh.h"
#import "OAMyBriefcaseViewCell.h"
#import "UITableView+Custom.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

#import "ServiceConnect.h"
#import "DownLoadHandle.h"
#import "PreviewFileHelper.h"
#import "GEAccessoryPreview.h"
#import "OAMyBriefcaseHtmlViewController.h"

#import "UITableView+Custom.h"

@interface OAMyBriefcaseViewController ()<SKSTableViewDelegate,GETableViewButtonCellDelagate>

@property (strong, nonatomic) NSMutableArray *resultData;
@property (strong, nonatomic) NSMutableArray *searchData;

@property (strong, nonatomic) NSMutableArray *classTypeData;
@property (assign, nonatomic) BOOL isChildItemOption;

@property (assign, nonatomic) NSInteger segmentActionState;
@property (strong, nonatomic) NSMutableDictionary *briefcaseTypeModel;

@property (strong, nonatomic) UIView *searchMainView;
@property (strong, nonatomic) UITableView *searchTableView;

@end

@implementation OAMyBriefcaseViewController
@synthesize tableView = _tableView;
@synthesize searchMainView = _searchMainView;
@synthesize searchTableView = _searchTableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"我的公文"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    self.classTypeData = [NSMutableArray array];
    
    self.tableView.SKSTableViewDelegate = self;
    self.tableView.shouldExpandOnlyOneCell = YES;
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    [self setupRefresh];//启动下拉
}

- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

//具体委托方法实例
-(void)segmentAction:(UISegmentedControl *)Seg
{
    NSInteger index = Seg.selectedSegmentIndex;
    self.segmentActionState = index;
    
    [self.resultData removeAllObjects];
    [self.tableView refreshData];
}

#pragma mark 网络获取数据

- (void)getNetWorkDataBriefcaseType
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    
    //0、已发送公文，1、收到公文
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userInfo.Id forKey:@"userid"];
    [model setValue:userInfo.PostId forKey:@"postid"];
    [model setValue:@"1" forKey:@"type"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_DocumentTypeCount" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView headerEndRefreshing];
        if(result.resultArray && result.resultArray.count>0){
            NSMutableArray *newArray = [NSMutableArray array];
            for (NSDictionary *dic in result.resultArray)
                [newArray addObject:[NSMutableDictionary dictionaryWithDictionary:dic]];
            
            [self.classTypeData removeAllObjects];
            [self.classTypeData addObjectsFromArray:newArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView refreshData];
        } else {
            [self.tableView setTableViewNotDataDrawText:@"暂无公文" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"==failed===%@",error);
        [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===abnormal==%@",error);
        [self errorInfoViewText:@"无法连接网络"];
    }];
}

- (void)getNetWorkDataIsReresh:(BOOL)isReresh state:(NSNumber*)state end:(NSNumber*)end
{
    //获取用户登录信息
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSNumber *briefcaseType  = [self.briefcaseTypeModel objectFormatForKey:@"officiaType"];
    NSString *search = [NSString stringWithFormat:@"officiaType|%@", briefcaseType];
    
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userInfo.Id forKey:@"userid"];
    [model setValue:userInfo.PostId forKey:@"postid"];
    [model setValue:search forKey:@"searchVal"];
    [model setValue:state forKey:@"between"];
    [model setValue:end forKey:@"and"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_DocumentReceived" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(isReresh) [self.tableView headerEndRefreshing];
        else [self.tableView footerEndRefreshing];
        //添加数据，刷新页面
        if(result.resultArray && result.resultArray.count>0){
            NSMutableArray *newArray = [NSMutableArray array];
            for (NSDictionary *dic in result.resultArray)
                [newArray addObject:[NSMutableDictionary dictionaryWithDictionary:dic]];
            
            if(isReresh) [self.resultData removeAllObjects];
            [self.resultData addObjectsFromArray:newArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView refreshData];
        } else if(isReresh){
            [self.tableView setTableViewNotDataDrawText:@"暂无公文" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        if(isReresh)[self errorInfoViewText:@"无法连接网络"];
    }];
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    if(!self.isChildItemOption){
        [self getNetWorkDataBriefcaseType];
    } else {
        NSNumber *stateNumber = [NSNumber numberWithInteger:1];
        NSNumber *endNumber = [NSNumber numberWithInteger:10];
        [self getNetWorkDataIsReresh:YES state:stateNumber end:endNumber];
    }
}

- (void)footerRereshing
{
    if(!self.isChildItemOption){
        [self.tableView footerEndRefreshing];
    } else {
        NSNumber *stateNumber = [NSNumber numberWithInteger:self.resultData.count + 1];
        NSNumber *endNumber = [NSNumber numberWithInteger:self.resultData.count + 10];
        [self getNetWorkDataIsReresh:NO state:stateNumber end:endNumber];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.isChildItemOption) return self.resultData.count;
    else return self.classTypeData.count;
}

- (NSInteger)tableView:(SKSTableView *)tableView numberOfSubRowsAtIndexPath:(NSIndexPath *)indexPath
{
    return 1;
}

- (UITableViewCell *)tableView:(SKSTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(!self.isChildItemOption){
        static NSString *CellIdentifierOne = @"OAMyBriefcaseClassCell";
        OAMyBriefcaseClassCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierOne];
        if (!cell)
            cell = [[OAMyBriefcaseClassCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierOne];
        
        NSDictionary *model = [self.classTypeData objectAtIndex:indexPath.row];
        cell.titleLable.text = [model objectFormatStringForKey:@"officiaTypename"];
        cell.badgeButton.text = [model objectFormatStringForKey:@"isredsum"];
        
        NSInteger isredsum = [[model objectFormatForKey:@"isredsum"] integerValue];
        if (isredsum <= 0) cell.badgeButton.hidden = YES;
        else cell.badgeButton.hidden = NO;
        return cell;
        
    } else {
        static NSString *CellIdentifier = @"OAMyBriefcaseViewCell";
        OAMyBriefcaseViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell){
            cell = [[OAMyBriefcaseViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            [cell setExpandable:YES];
        }
        
        cell.openUpButton.object = indexPath;
        [cell.openUpButton addTarget:self action:@selector(openSelectRowSelector:) forControlEvents:UIControlEventTouchUpInside];
        
        NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
        cell.compLable.text = [model objectFormatStringForKey:@"officiaType"];
        cell.timeLable.text = [model objectFormatStringForKey:@"creationTime"];
        cell.peopleLable.text = [model objectFormatStringForKey:@"publisher"];
        
        //是否阅读标记
        NSInteger isRead = [[model objectFormatForKey:@"isRead"] integerValue];
        if(isRead <= 0){
            cell.readMark.hidden = YES;
            cell.titleLable.text = [model objectFormatStringForKey:@"officialName"];
        } else {
            NSString *title = [model objectFormatStringForKey:@"officialName"];
            cell.readMark.hidden = NO;
            cell.titleLable.text = [NSString stringWithFormat:@"         %@",title];
        }
        
        return cell;
    }
    
    return nil;
}

- (void)openSelectRowSelector:(GEObjectButton*)button
{
    NSIndexPath *indexPath = button.object;
    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //创建连接，预览文件
    NSMutableDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
    NSString *fileUrl = [mDictionary objectFormatStringForKey:@"officialPath"];
    NSString *wjName = [mDictionary objectFormatStringForKey:@"officialName"];
    NSString *officialPageUrl = [mDictionary objectFormatStringForKey:@"officialPageUrl"];
    
    //如果有officialPageUrl，跳转至网页显示
    if(officialPageUrl.length > 0){
        OAMyBriefcaseHtmlViewController *view = [[OAMyBriefcaseHtmlViewController alloc] initWithNibUrl:officialPageUrl];
        [self.navigationController pushViewController:view animated:YES];
        
    } else {
        PreviewFileHelper *preview = [[PreviewFileHelper alloc] init];
        [preview startPreviewExternalFile:fileUrl fileName:wjName];
    }
    
    //是否阅读标记
    NSInteger isRead = [[mDictionary objectFormatForKey:@"isRead"] integerValue];
    if(isRead > 0){//未读
        NSString *ids = [mDictionary objectFormatStringForKey:@"id"];
        [self submitMessageInfoId:ids model:mDictionary];
    }
}

- (UITableViewCell *)tableView:(SKSTableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"GETableViewButtonCell";
    GETableViewButtonCell *cell = [[GETableViewButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    [cell drawRectButtonName:@"预览" imageName:@"home_nav_left_serch" tagIndex:1];
    
    NSDictionary *model = [self.resultData objectAtIndex:indexPath.row];
    NSArray *fileArray = [model objectFormatForKey:@"fjJsiong"];
    if ([fileArray isKindOfClass:[NSArray class]] && fileArray.count > 0)
        [cell drawRectButtonName:@"附件" imageName:@"oa_read_info_btn.png" tagIndex:2];
    
    NSMutableDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
    NSString *officialPageUrl = [mDictionary objectFormatStringForKey:@"officialPageUrl"];
    if(officialPageUrl.length <= 0)
        [cell drawRectButtonName:@"下载" imageName:@"oa_down_file_btn.png" tagIndex:3];
    
    cell.delagate = self;
    [cell setIndexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.isChildItemOption) return 80;
    else return 60;
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Row_Section: %ld, Row:%ld, Subrow:%ld", (long)indexPath.section, indexPath.row, (long)indexPath.subRow);
    if(!self.isChildItemOption){
        self.isChildItemOption = YES;
        [self.tableView refreshData];
        
        NSMutableDictionary *model = [self.classTypeData objectAtIndex:indexPath.row];
        self.briefcaseTypeModel = model;
        self.itemTitleLable.text = [model objectFormatStringForKey:@"officiaTypename"];
        [self.tableView headerBeginRefreshing];
        
        //页面刷新动画.
        CATransition *animation = [CATransition animation];
        [animation setDuration:0.30f];
        [animation setTimingFunction:[CAMediaTimingFunction
                                      functionWithName:kCAMediaTimingFunctionLinear]];
        [animation setType:kCATransitionPush];
        [animation setSubtype: kCATransitionFromRight];
        [self.tableView.layer addAnimation:animation forKey:@"pullTableView"];
    }
}

#pragma mark - GETableViewButtonCellDelagate

- (void) cellButtonEvent:(NSIndexPath*)indexPath tagIndex:(int)tagIndex
{
    NSDictionary *mDictionary = [self.resultData objectAtIndex:indexPath.row];
    if (tagIndex == 1) {//预览
        //创建连接，预览文件
        NSString *fileUrl = [mDictionary objectFormatStringForKey:@"officialPath"];
        NSString *wjName = [mDictionary objectFormatStringForKey:@"officialName"];
        NSString *officialPageUrl = [mDictionary objectFormatStringForKey:@"officialPageUrl"];
        
        //如果有officialPageUrl，跳转至网页显示
        if(officialPageUrl.length > 0){
            OAMyBriefcaseHtmlViewController *view = [[OAMyBriefcaseHtmlViewController alloc] initWithNibUrl:officialPageUrl];
            [self.navigationController pushViewController:view animated:YES];
            
        } else {
            PreviewFileHelper *preview = [[PreviewFileHelper alloc] init];
            [preview startPreviewExternalFile:fileUrl fileName:wjName];
        }
        
    } else if (tagIndex == 2) {//附件
        NSArray *fileArray = [mDictionary objectFormatForKey:@"fjJsiong"];
        GEAccessoryPreview *showAccessory = [[GEAccessoryPreview alloc] init];
        [showAccessory showAccessoryTableAlert:fileArray];
        
    } else if (tagIndex == 3) {//下载
        //创建连接，下载文件
        NSString *wjPath = [mDictionary objectFormatStringForKey:@"officialPath"];
        NSString *wjName = [mDictionary objectFormatStringForKey:@"officialName"];
        DownLoadHandle *downLoad = [[DownLoadHandle alloc] init];
        [downLoad startDownExternalFile:wjPath fileName:wjName];
    }
}

#pragma mark - back button

- (void)backButtonEvent:(id)sender
{
    if (self.isChildItemOption) {
        self.isChildItemOption = NO;
        self.itemTitleLable.text = @"所有归档";
        [self.tableView refreshData];
        
        //停止刷新数据
        [self stopRefresh];
        [self.resultData removeAllObjects];
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        
        //页面刷新动画
        CATransition *animation = [CATransition animation];
        [animation setDuration:0.30f];
        [animation setTimingFunction:[CAMediaTimingFunction
                                      functionWithName:kCAMediaTimingFunctionLinear]];
        [animation setType:kCATransitionPush];
        [animation setSubtype: kCATransitionFromLeft];
        [self.tableView.layer addAnimation:animation forKey:@"pullTableView"];
    } else {
        [super backButtonEvent:sender];
    }
}

#pragma mark - 已读提交

- (void)submitBriefcaseInfoId:(NSString*)ids serialnumber:(NSString*)serialnumber index:(NSInteger)index
{
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:ids forKey:@"id"];
    [model setValue:userInfo.Id forKey:@"userid"];
    [model setValue:serialnumber forKey:@"Serialnumber"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_delMyApplication" dataArray:model];
    [content showMBProgressHUD:self.navigationController labelText:@"正在删除"];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if (result.resultArray && result.resultArray.count>0) {
            NSDictionary *resultArray = [result.resultArray firstObject];
            NSInteger resultState = [[resultArray objectFormatForKey:@"result"] integerValue];
            if (resultState == 1){
                [self showSuccessHUDText:@"删除成功"];
                [self stopRefresh];
                [self.resultData removeObjectAtIndex:index];
                [self.tableView refreshData];
                [self.tableView headerBeginRefreshing];
                return;
            }
        }
        [self showErrorHUDText:@"删除失败"]; return;
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"删除失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"网络异常"];
    }];
}


#pragma mark - 已读提交

- (void)submitMessageInfoId:(NSString*)msgid model:(NSMutableDictionary *)value
{
    //提交已读 1、消息 2、公文
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:msgid forKey:@"msgid"];
    [model setValue:userInfo.Id forKey:@"userid"];
    [model setValue:@2 forKey:@"type"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_MsgRead" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if (result.resultArray && result.resultArray.count>0) {
            NSDictionary *resultArray = [result.resultArray firstObject];
            NSInteger resultState = [[resultArray objectFormatForKey:@"result"] integerValue];
            if (resultState == 1){
                NSInteger noReadCount = [self.briefcaseTypeModel objectFormatIntegerForKey:@"isredsum"];
                noReadCount = noReadCount <=0 ? 0 : (noReadCount - 1);
                NSNumber *redsum = [NSNumber numberWithInteger:noReadCount];
                [self.briefcaseTypeModel setObject:redsum forKey:@"isredsum"];
                
                [value setObject:[NSNumber numberWithInteger:0] forKey:@"isRead"];
                [self.tableView reloadData];
            }
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===submitMessageInfoId==%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"==submitMessageInfoId===%@",error);
    }];
}

@end
